//
//  NetworkTools.swift
//  dwdWb
//
//  Created by Dengdwd on 15/10/7.
//  Copyright © 2015年 dwd. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
enum RequestType: String {
   case GET = "GET"
   case POST = "POST"
}

private let APP_URLSTRING = "https://api.weibo.com/"
class NetworkTools: AFHTTPSessionManager {

    let Wb_client_id = "2619316005"
    let Wb_redirect_uri = "http://www.baidu.com"
    let Wb_client_secret = "1e0df0bd17d3db36fc6e1ce4fe4e3cb1"
    
    static let sharedTools : NetworkTools = {
        let url = NSURL(string: APP_URLSTRING)!
        let tools = NetworkTools(baseURL: url)
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
        }()

    
    func updateText(status:String?,image:UIImage?) {
    
        if let account = UserAcount.loadUserData() where account.access_token != nil {
            var urlString = ""
            var params = [String:AnyObject]()
            SVProgressHUD.show()
            if image == nil {
                urlString = "2/statuses/update.json"
                params = ["access_token":account.access_token!,"status":status!]
                POST(urlString, parameters: params, success: { (_, result) -> Void in
            NSNotificationCenter.defaultCenter().postNotificationName("closeComposeBtn", object: nil)
                    }) { (_, error) -> Void in
            NSNotificationCenter.defaultCenter().postNotificationName("requestError", object: nil)
                }
            }else{
            urlString = "2/statuses/upload.json"
            params = ["access_token":account.access_token!,"status":status!]
                POST(urlString, parameters: params, constructingBodyWithBlock: { (formdata) -> Void in
                    let data = UIImagePNGRepresentation(image!)!
                    formdata.appendPartWithFileData(data, name: "pic", fileName: "哈哈", mimeType: "application/octet-stream")
                    }, success: { (_, result) -> Void in
            NSNotificationCenter.defaultCenter().postNotificationName("closeComposeBtn", object: nil)
                    }, failure: { (_, error) -> Void in
            NSNotificationCenter.defaultCenter().postNotificationName("requestError", object: nil)            
                })
            }
        }
    }
    
    func oAuthPage() ->NSURL {
        let pageURL = "https://api.weibo.com/oauth2/authorize"
        let urlString = pageURL + "?" + "client_id=" + Wb_client_id + "&" + "redirect_uri=" + Wb_redirect_uri
        return NSURL(string: urlString)!
    }
    
    func loadToken(code:String,completion:(dict:[String:AnyObject]?,error:NSError?) ->()) {
    
        let urlString = "oauth2/access_token"
        
        let params = ["client_id":Wb_client_id,"client_secret":Wb_client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":Wb_redirect_uri]
        requestToken(.POST, urlString: urlString, params: params, completion: completion)
 
    }
    func loadUserInfo(access_token:String,uid:String,completion:(dict:[String:AnyObject]?,error:NSError?) ->()) {
    let urlString = "2/users/show.json"
        
    let params = ["access_token":access_token,"uid":uid]
       requestToken(.GET, urlString: urlString, params: params, completion: completion)
            }
    func requestToken (type: RequestType,urlString: String,params: [String:AnyObject]? = nil,completion: (dict:[String:AnyObject]?,error:NSError?) ->()) {
        let successCallBack = { (task:NSURLSessionDataTask, result:AnyObject) -> () in
            if let dict = (result as? [String:AnyObject]) {
                completion(dict: dict, error: nil)
            }else {
                completion(dict:nil, error: NSError(domain: "com.baidu.error.data", code: -1001, userInfo:["error":"数据解析错误"]))
            }
        }
        let faildCallBack = {
             (task:NSURLSessionDataTask, error:NSError) -> () in
                completion(dict:nil,error:error)
                print(error)
            }
        
        if type == RequestType.GET {
       GET(urlString, parameters: params, success: successCallBack, failure: faildCallBack)
        }else{
            POST(urlString, parameters: params, success: successCallBack, failure: faildCallBack)
            }
        }
    

    deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
}
